package com.siemens.industrial.web.mvc.service.admin;

import com.siemens.industrial.web.mvc.dao.admin.DBBackupLogDao;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Yipin on 2016/11/23.
 */
@Service
public class DBBackupLogService {
    @Resource
    DBBackupLogDao dbBackupLogDao;

    @Resource
    JdbcTemplate jdbcTemplate;

    public List<Map<String,Object>> getDBBackupLog(){
        return dbBackupLogDao.getDBBackupLog();
    }

    //dataTable search backup log
    public Map<String,Object> getDBBackupLogByDataTable(HttpServletRequest request){
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String, Object>> list;

        String totalSql = "SELECT COUNT(1) FROM `siemens`.`db_backup_log` WHERE 1=1\n";
        String sql = "SELECT \n" +
                "    DATE_FORMAT(backup_time, '%Y-%m-%d %H:%i:%s') backup_time,\n" +
                "    backup_type,\n" +
                "    backup_file,\n" +
                "    CASE\n" +
                "        WHEN backup_status = - 1 THEN '进行中'\n" +
                "        WHEN backup_status = 0 THEN '成功'\n" +
                "        WHEN backup_status = 1 THEN '失败'\n" +
                "    END backup_status\n" +
                "FROM\n" +
                "    `siemens`.`db_backup_log`\n" +
                "    where 1=1";
        int total = jdbcTemplate.queryForObject(totalSql, Integer.class);
        int filteredCount = total;
        if (!dt.getSearch().equals("")) {
            String status = "";
            if("进行中".matches(dt.getSearch())){
                status = "-1";
            }else if("成功".matches(dt.getSearch())){
                status = "0";
            }else if("失败".matches(dt.getSearch())){
                status = "1";
            }
            String search = " and (backup_time like '%" + dt.getSearch() + "%' or backup_type like '%" + dt.getSearch() + "%' or backup_file like '%" + dt.getSearch() + "%' or backup_status like '%" + status + "%')";
            sql += search;
            filteredCount = jdbcTemplate.queryForObject(totalSql + search, Integer.class);
        }

        if (!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")) {
            String order = " ORDER BY `" + dt.getOrderDBColumn() + "` " + dt.getOrderAscOrDesc();
            sql += order;
        }

        String limit = " limit " + dt.getStart() + "," + dt.getLength();
        sql += limit;

        list = jdbcTemplate.queryForList(sql);
        return dt.buildResponse(filteredCount, total, list);
    }
}